package net.sourceforge.openclixml.ext;

import net.sourceforge.openclixml.EvaluationFailedException;
import net.sourceforge.openclixml.EvaluationNotSupportedException;
import net.sourceforge.openclixml.domcomparator.DomComparator;
import net.sourceforge.openclixml.environment.IEnvironment;

import org.w3c.dom.Document;

import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.xml.xpath.XPathExpressionException;


/**
 *
 * @version $Revision: 47 $
 * @author dominikjungo
 *
 * Last changed: $Date: 2008-02-03 22:01:31 +0100 (Sun, 03 Feb 2008) $
 * The License for this file can be found in doc/Licenses/license-OpenCliXML.txt
 */
public class PredicateType extends net.sourceforge.openclixml.autogen.PredicateType {
    private LinkingType getOp1() {
        return (LinkingType) getPredicateGroup().get(0);
    }

    private LinkingType getOp2() {
        return (LinkingType) getPredicateGroup().get(1);
    }

    private Object evalOp1(final IEnvironment<String, String> environment,
        final Map<String, Document> systemUnderTest)
        throws EvaluationFailedException, XPathExpressionException {
        try {
            //TODO not eval but...
            return getOp1().getFragment(environment, systemUnderTest);
        } catch (EvaluationNotSupportedException e) {
            throw new EvaluationFailedException("Evaluation of op1 failed", e);

            //TODO eval the locator
            //return getOp1()
        }
    }

    private Object evalOp2(final IEnvironment<String, String> environment,
        final Map<String, Document> systemUnderTest)
        throws EvaluationFailedException, XPathExpressionException {
        try {
            return getOp2().getFragment(environment, systemUnderTest);
        } catch (EvaluationNotSupportedException e) {
            throw new EvaluationFailedException("Evaluation of op2 failed", e);

            //TODO eval the locator
            //return getOp2()
        }
    }

    protected final int evalAndCompare(
        final IEnvironment<String, String> environment,
        final Map<String, Document> systemUnderTest)
        throws EvaluationFailedException {
        try {
            return new DomComparator().compare(evalOp1(environment,
                    systemUnderTest), evalOp2(environment, systemUnderTest));
        } catch (XPathExpressionException ex) {
            Logger.getLogger(PredicateType.class.getName())
                  .log(Level.SEVERE, null, ex);
            throw new EvaluationFailedException("XPath evaluation failed", ex);
        }
    }
}
